const rightClickMenu = {
  beforeMount: function (el, binding, vnode) {
    el.addEventListener("contextmenu", function (event) {
      event.preventDefault();

      if (binding.instance.menuVisible) {
        return false; // 如果菜单已经显示，则不再重复弹出
      }
      binding.instance.menuVisible = true; // 设置菜单为显示状态

      const menuItems = binding.value || [];

      let menu = document.createElement("ul");
      menu.style.position = "fixed";
      menu.style.zIndex = 999;
      menu.style.top = event.clientY + "px";
      menu.style.left = event.clientX + "px";

      menuItems.forEach((item) => {
        const menuItem = document.createElement("li");
        menuItem.innerText = item.text;
        menuItem.addEventListener("click", function () {
          binding.instance.menuVisible = false; // 点击菜单项后隐藏菜单
          item.handler();
        });
        menu.appendChild(menuItem);
      });
      document.body.appendChild(menu);

      function deleteMenu(e) {
        if (!el.contains(e.target)) {
          binding.instance.menuVisible = false;
          if (menu) document.body.removeChild(menu);
          menu = null;
        }
      }
      // 点击其他地方时隐藏菜单
      el.__vueDeleteMenu__ = deleteMenu;
      document.addEventListener("click", deleteMenu);
    });
  },
  unmounted(el) {
    document.removeEventListener("click", el.__vueDeleteMenu__);
    delete el.__vueDeleteMenu__;
  },
}

export default rightClickMenu;